<?php

namespace app\admin\controller\cms;

use app\admin\model\cms\ChartTableModel;
use app\api\library\Service;
use app\common\controller\Backend;
use think\Db;

/**
 * 自定义表单数据表
 *
 * @icon fa fa-circle-o
 */
class Diydata extends Backend
{

    /**
     * 自定义表单模型对象
     */
    protected $diyform = null;
    /**
     * 定义表单数据表模型
     * @var null
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        
        $diyform_id = $this->request->param('diyform_id');
        $this->diyform = \app\admin\model\cms\Diyform::get($diyform_id);
        if (!$this->diyform) {
            $this->error('未找到对应自定义表单');
        }
        $this->model = new \app\admin\model\cms\Diydata([], $this->diyform);
        $this->assignconfig('diyform_id', $diyform_id);
    }

    /**
     * 查看
     */
    public function index()
    {

        $pro_diyform_id = $this->diyform['id'];//图表id
        //根据图表id得到本图表使用的字段
        $diyform = \app\admin\model\cms\Diyform::where('id',$pro_diyform_id)->find();

        $fields_arr = [];
        foreach($diyform['fields'] as $v){
            $fields_arr[] = json_decode(trim($v,'[]'),true);
        }

        $fields = [];
        $field_arr = [
            'id',
            'datetime',
            'createtime',
            'updatetime',
            'memo',
        ] ;
        foreach ($fields_arr as $k => $v) {
            $field_arr[] = key($v);
            $fields[] = [
                'field' => key($v),
                'title' => array_values($v)[0],
                'type' => 'string',
                'content' => [
                    ' value1|title1',
                    ' value2|title2',
                ]
            ];
        }

        $this->assignconfig('fields', $fields);
        $where_diyformList = [];


        $config = ['diyformdatalimit'=> "all",'spiderrecord'=>0];

        if ($config['diyformdatalimit'] != 'all') {
            $this->dataLimit = $config['diyformdatalimit'];
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $where_diyformList[$this->dataLimitField] = ['in', $adminIds];
            }
            $this->dataLimit = false;
        }

        $diyformList = \app\admin\model\cms\Diyform::where($where_diyformList)->select();
        $this->view->assign('diyform', $this->diyform);
        $this->view->assign('diyformList', $diyformList);


        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        $limit = $this->request->param(10,10);
        $offset = $this->request->param(0,0);
        $order = $this->request->param('desc','desc');
//        [$where, $sort, $order, $offset, $limit] = $this->buildparams();



        $list = Db::table($diyform['table'])->field($field_arr)
            ->order('id', 'desc')
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function index_COPY()
    {
        $fieldsList = \app\admin\model\cms\Fields::where('source', 'diyform')->where('source_id', $this->diyform['id'])->where('type', '<>', 'text')->order('id asc')->select();
        $fields = [];
        foreach ($fieldsList as $index => $item) {
            $fields[] = ['field' => $item['name'], 'title' => $item['title'], 'type' => $item['type'], 'content' => $item['content_list']];
        }
        $this->assignconfig('fields', $fields);
        $where = [];


        $config = ['diyformdatalimit'=> "all",'spiderrecord'=>0];
        if ($config['diyformdatalimit'] != 'all') {
            $this->dataLimit = $config['diyformdatalimit'];
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $where[$this->dataLimitField] = ['in', $adminIds];
            }
            $this->dataLimit = false;
        }

        $diyformList = \app\admin\model\cms\Diyform::where($where)->select();
        $this->view->assign('diyform', $this->diyform);
        $this->view->assign('diyformList', $diyformList);
        return parent::index();
    }

    /**
     * 添加
     */
    public function add()
    {

        $table = str_replace('fa_', '', $this->diyform['table']);
        $pro_diyform_id = $this->diyform['id'];//图表id
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $result = db($table)->insert($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        //根据图表id得到本图表使用的字段
        $diyform = \app\admin\model\cms\Diyform::where('id',$pro_diyform_id)->find();

        $field_list = [];
        foreach($diyform['fields'] as $v){
            $field_list[] = json_decode(trim($v,'[]'),true);
        }
        $field_list = call_user_func_array('array_merge', $field_list);//二维数组转一维数组

        $this->view->assign("field_list", $field_list);

        return $this->view->fetch('cms/diydata/add');
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {

        $table = str_replace('fa_', '', $this->diyform['table']);
        $row = db($table)->where('id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();

        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $result = db($table)->where('id',$ids)->update($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $pro_diyform_id = $this->diyform['id'];//图表id
        //根据图表id得到本图表使用的字段
        $diyform = \app\admin\model\cms\Diyform::where('id',$pro_diyform_id)->find();

        $field_list = [];
        foreach($diyform['fields'] as $v){
            $field_list[] = json_decode(trim($v,'[]'),true);
        }
        $field_list = call_user_func_array('array_merge', $field_list);//二维数组转一维数组

        $this->view->assign("field_list", $field_list);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");

        $table = str_replace('fa_', '', $this->diyform['table']);

        if ($ids) {
            $count = db($table)->where('id','in',$ids)->delete();
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
